﻿namespace Homework19
{
    internal class Program
    {
        /// <summary>
        /// 查C盘中多少个txt文件
        /// </summary>
        /// <param name="args"></param>
        static void Main()
        {
            //选择c盘
            string rootDirectory = @"C:\";
            int txtFileCount = CountTxtFiles(rootDirectory);
            Console.WriteLine($"There are {txtFileCount} .txt files in the C: drive.");
        }

        static int CountTxtFiles(string directory)
        {
            int count = 0;

            try
            {
                // 获取当前目录中的文件
                string[] files = Directory.GetFiles(directory, "*.txt");
                count += files.Length;

                // 获得子目录中的文件
                string[] subdirectories = Directory.GetDirectories(directory);

                foreach (string subdirectory in subdirectories)
                {
                    // 递归
                    count += CountTxtFiles(subdirectory);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                // 不可访问的文件
                Console.WriteLine($"不可访问文件: {directory}");
            }
            catch (Exception ex)
            {
                // 其他情况
                Console.WriteLine($"访问错误: {ex.Message}");
            }

            return count;
        }
    }
}